var FillandCutPolygon;
var terrainProvider;
// 定义填挖方的基准面高度
var excavateHeight = 50; // 开挖高度
var buryHeight = 50; // 填埋高度

/**
 * 获取要素的范围
 * @param {*} positions 
 */
function getBorder(positions) {
    var xmin, ymin, xmax, ymax;
    for (var i = 0; i < positions.length; i++) {
        var position = positions[i];
        var x = position.x;
        var y = position.y;
        if (i == 0) {
            xmin = xmax = x;
            ymin = ymax = y;
        } else {
            xmin = xmin > x ? x : xmin;
            xmax = xmax < x ? x : xmax;
            ymin = ymin > y ? y : ymin;
            ymax = ymax < y ? y : ymax;
        }
    }
    return [xmin, ymin, xmax, ymax];
}

function FillandCutOnload() {
    viewer.scene.globe.depthTestAgainstTerrain = true;
    $('#FillandCut_draw').click(function() {
        FillandCut_clear();
        excavateHeight = $("#excavateHeight_input").val();
        buryHeight = $("#buryHeight_input").val();
        if (!excavateHeight || !buryHeight) {
            showMsgLayer("开挖高度/填埋高度为必填项！");
            return;
        }
        excavateHeight = parseFloat($("#excavateHeight_input").val());
        buryHeight = parseFloat($("#buryHeight_input").val());
        tracker.trackPolygon(function(position) {
            tracker && tracker.clear();
            var array = [].concat(position);
            positions = [];
            for (var i = 0, len = array.length; i < len; i++) {
                var cartographic = Cesium.Cartographic.fromCartesian(array[i]);
                var longitude = Cesium.Math.toDegrees(cartographic.longitude);
                var latitude = Cesium.Math.toDegrees(cartographic.latitude);
                var h = cartographic.height;
                if (positions.indexOf(longitude) == -1 && positions.indexOf(latitude) == -1) {
                    positions.push({
                        x: longitude,
                        y: latitude,
                        z: h
                    });
                }
            }
            var points = getPointsForPositions(positions);
            var draw_polygon = turf.polygon([points]);
            var border = getBorder(positions);
            var entity = viewer.entities.add({
                polygon: {
                    hierarchy: array,
                    height: buryHeight,
                    extrudedHeight: excavateHeight,
                    material: Cesium.Color.RED.withAlpha(0.5),
                    outline: true,
                    closeTop: false
                }
            });
            viewer.trackedEntity = entity;
            //剖分施工区域，计算每个区域的面积与填挖高度
            var subdivisionCell = 0.0001; // 剖分精度自定义//设置剖分最小单元 0.01°
            // 存储所有的剖分矩形
            var subRectangles = [];
            for (var i = border[0]; i <= border[2]; i = i + subdivisionCell) {
                for (var j = border[1]; j <= border[3]; j = j + subdivisionCell) {
                    var subRectangle = new Cesium.Rectangle(
                        Cesium.Math.toRadians(i),
                        Cesium.Math.toRadians(j),
                        Cesium.Math.toRadians(i + subdivisionCell),
                        Cesium.Math.toRadians(j + subdivisionCell)
                    );
                    subRectangles.push(subRectangle);
                    // 可视化部分---剖分面
                    // viewer.entities.add({
                    //     rectangle: {
                    //         coordinates: subRectangle,
                    //         material: Cesium.Color.fromRandom().withAlpha(0.5),
                    //         height: buryHeight,
                    //         extrudedHeight: excavateHeight,
                    //     }
                    // });
                }
            }
            // 计算每个矩形的中心点作为这个矩形的代表
            var subRectanglesCenterPoints = [];
            subRectangles.forEach(subRectangle => {
                var centerPoint = Cesium.Cartographic.fromRadians((subRectangle.west + subRectangle.east) / 2, (subRectangle
                    .north +
                    subRectangle.south) / 2);
                var point = turf.point([Cesium.Math.toDegrees(centerPoint.longitude), Cesium.Math.toDegrees(centerPoint.latitude)]);
                if (turf.booleanPointInPolygon(point, draw_polygon)) {
                    subRectanglesCenterPoints.push(centerPoint);
                    // 可视化部分 ---中心线
                    var position = centerPoint.clone();
                    position.height = buryHeight;
                    var position1 = centerPoint.clone();
                    position1.height = excavateHeight;
                    viewer.entities.add({
                        polyline: {
                            positions: [Cesium.Cartographic.toCartesian(position), Cesium.Cartographic.toCartesian(position1)],
                            material: Cesium.Color.fromRandom().withAlpha(0.5),
                            width: 5
                        }
                    });
                } else {
                    console.log("该点不在范围内");
                }
            });
            // 所有高度
            var heights = [];
            // 采样每个中心点到达地表的高度
            //var promise = Cesium.sampleTerrainMostDetailed(terrainProvider, subRectanglesCenterPoints);
            var promise = Cesium.sampleTerrain(viewer.terrainProvider, 11, subRectanglesCenterPoints);
            Cesium.when(promise, function(updatedPositions) {
                updatedPositions.forEach(point => {
                    heights.push(point.height);
                });
                // 开始计算土方
                var excavateVolumes = 0; // 挖方
                var buryVolumes = 0; // 填埋
                // 1.计算每个矩形的长、宽
                for (var i = 0; i < subRectangles.length; i++) {
                    var subRectangle = subRectangles[i];
                    var leftBottom = Cesium.Cartesian3.fromRadians(subRectangle.west, subRectangle.south);
                    var leftTop = Cesium.Cartesian3.fromRadians(subRectangle.west, subRectangle.north);
                    var rightBottom = Cesium.Cartesian3.fromRadians(subRectangle.east, subRectangle.south);
                    var height = Cesium.Cartesian3.distance(leftBottom, leftTop); // 宽
                    var width = Cesium.Cartesian3.distance(leftBottom, rightBottom); // 长

                    // 挖方
                    if (heights[i] > excavateHeight) { // 如果地形高度大于开挖高度才需要开挖
                        var excavateVolume = width * height * (heights[i] - excavateHeight);
                        excavateVolumes += excavateVolume;
                    }
                    // 填埋
                    if (heights[i] < buryHeight) { // 如果地形高度小于填埋高度才需要填埋
                        var buryVolume = width * height * (buryHeight - heights[i]);
                        buryVolumes += buryVolume;
                    }
                }
                $("#excavateVolumes_input").val(Math.round(excavateVolumes * 100) / 100);
                $("#buryVolumes_input").val(Math.round(buryVolumes * 100) / 100);
            });
        });
    })

    $('#FillandCut_clear').click(function() {
        FillandCut_clear();
    })
}

function FillandCut_clear(clear) {
    $("#excavateVolumes_input").val("");
    $("#buryVolumes_input").val("");
    if (!clear) { removeAllEntities(); }
    tracker && tracker.clear();
}

/**
 * 转换turf 面要素数据
 * @param {*} positions 
 */
function getPointsForPositions(positions) {
    var points = [];
    for (var i = 0; i < positions.length; i++) {
        points.push([positions[i].x, positions[i].y]);
    }
    points.push(points[0]);
    return points;
}